#include <joystick.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc > 2)
    {
        printf("usage: %s [<device>]", argv[0]);
        exit(0);
    }

    const char *deviceName;
    if(argc == 1)
    {
        deviceName = "/dev/input/js0";
    }
    else
    {
        deviceName = argv[1];
    }
    Joystick joystick(deviceName);

    char *device = joystick.getDevice();
    printf("Reading From: %s\n", device);
    delete []device;

    int version = joystick.getVersion();
    printf("Driver version is %d.%d.%d.\n", version >> 16, (version >> 8) & 0xff, version & 0xff);

    char *name = joystick.getName();
    int numAxes = joystick.getNumAxes();
    uint8_t *axmap = joystick.getAxmap();
    int numButtons = joystick.getNumButtons();
    uint16_t *btnmap = joystick.getBtnmap();

    printf("Joystick (%s) has %d axes (", name, numAxes);
    for(int i = 0; i < numAxes; i++)
    {
        printf("%s%s", i > 0 ? ", " : "", Joystick::axis_name[axmap[i]]);
    }
    printf(")\n");

    printf("and %d buttons (", numButtons);
    for(int i = 0; i < numButtons; i++)
    {
        printf("%s%s", i > 0 ? ", " : "", Joystick::button_name[btnmap[i] - BTN_MISC]);
    }
    printf(").\n");

    delete []name;
    delete []axmap;
    delete []btnmap;

    int *axis = new int[numAxes];
    char *button = new char[numButtons];

    while(true)
    {
        printf("\r");

        if(numAxes > 0)
        {
            printf("Axes: ");
            for (int i = 0; i < numAxes; i++)
            {
                printf("%2d:%6d ", i, axis[i]);
            }
        }

        if(numButtons > 0)
        {
            printf("Buttons: ");
            for (int i = 0; i < numButtons; i++)
            {
                printf("%2d:%s ", i, button[i] ? "on " : "off");
            }
        }
    }

    delete []axis;
    delete []button;

    return 0;
}

